﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace Xray.Common
{
    public class ContainerXrayServiceClient : ClientBase<IContainerXrayService>, IContainerXrayService, IDisposable
    {
        /// <summary>
        /// use this to create the service, it will mean the client application 
        /// does not require a WCF section in the config file
        /// </summary>
        /// <returns>the client service</returns>
        public static ContainerXrayServiceClient Create()
        {
            EndpointAddress endpointAddress = new EndpointAddress("http://localhost:8999/xray");
            Binding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);

            return new ContainerXrayServiceClient(binding, endpointAddress);
        }

        #region ctors

        public ContainerXrayServiceClient()
        {
        }

        public ContainerXrayServiceClient(string endpointConfigurationName) :
            base(endpointConfigurationName)
        {
        }

        public ContainerXrayServiceClient(string endpointConfigurationName, string remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
        {
        }

        public ContainerXrayServiceClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
        {
        }

        public ContainerXrayServiceClient(Binding binding, EndpointAddress remoteAddress) :
            base(binding, remoteAddress)
        {
        }

        #endregion

        /// <summary>
        /// Update the component model
        /// </summary>
        /// <param name="model">the entire current model (not a delta)</param>
        public void Update(Model model)
        {
            this.Channel.Update(model);
        }

        /// <summary>
        /// Clears the current model. allowing to start from scratch
        /// </summary>
        public void ClearModel()
        {
            this.Channel.ClearModel();
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            if (State == CommunicationState.Faulted)
            {
                Abort();
            }
            else
            {
                try
                {
                    Close();
                }
                catch
                {
                    Abort();
                }
            }
        }
    }
}